// 和平精英 首图 详情图 生成
import {
  getURLBase64Image,
  loadImages,
  drawImagesAreaBg,
  drawBgBorder,
} from "./getUrlImg";
import {setPageImgArr} from "./common"

// 去除相同sid的皮肤  保留第一个出现的
function uniqueBySid(arr) {
  const seen = new Map();
  return arr.filter(item => {
    if (!seen.has(item.sid)) {
      seen.set(item.sid, true);
      return true;
    }
    return false;
  });
}

// 生成和平精英首图
export async function makeTitleImgHpjy(data, list, attrs) {
  // console.log("%c Line:12 🌰 attrs", "color:#2eafb0", attrs);
  // console.log("%c Line:12 🥛 list", "color:#ea7e5c", list);
  // console.log("%c Line:12 🍅 data", "color:#33a5ff", data);
  // console.log("%c Line:6 🍊 attrs", "color:#93c0a4", attrs);
  // data = smock.data
  // list = smock.list
  // attrs = smock.attrs
  return new Promise(async (resolve, reject) => {
    // 取出已选择项
    let arr = [];
    let sm = "";
    let zsk = "";
    let hongzhuang = []
    let hongche = []
    let fenzhuang = []
    let remenzi = []
    let fenqiang = []
    list = list.split(",");
    if (!list || list == []) {
      reject("多选不能为空");
    }
    if (list && list.length) {
      attrs.forEach(async (item1) => {
        if (item1.aavName == "f10") {
          item1.childAttributes.forEach(async (item2) => {
            if (item2.id == data.f10) {
              sm = item2.fieldName;
            }
          });
        }
        if (item1.aavName == "f14") {
          item1.childAttributes.forEach(async (item2) => {
            if (item2.id == data.f14) {
              zsk = item2.fieldName;
            }
          });
        }
        if (item1.fieldType == "checkbox" && item1.isEnable === "0") {
          
          item1.childAttributes.forEach(async (item2) => {
            if (list.indexOf(String(item2.id)) > -1 && item2.imgUrl) {
              if(item1.aavName == "f24"){
                // 红装
                hongzhuang.push(item2);
              }else
              if(item1.aavName == "f2"&&item2.kz1>6){
                // 红车
                hongche.push(item2);
              }else
              if(item1.aavName == "f5"&&item2.kz1>5&&item2.kz2!=2){
                //稀有 粉装
                fenzhuang.push(item2);
              }else
              if(item1.aavName == "f6"||item1.aavName == "f29"){
                // 热门紫
                remenzi.push(item2);
              }else
              if(item1.aavName == "f1"&&item2.kz1>5){
                // 粉枪
                fenqiang.push(item2);
              }else{
                arr.push(item2);
              }
              
            }
          });
        }
      });
    }
    // 将皮肤组合在一个数组
    // 先排序
    hongzhuang.sort((a, b) => {return (b.kz1||0) - (a.kz1||0)});
    fenzhuang.sort((a, b) => {return (b.kz1||0) - (a.kz1||0)});
    arr.sort((a, b) => {return (b.kz1||0) - (a.kz1||0)});
    arr = hongzhuang.concat(hongche).concat(remenzi).concat(fenzhuang).concat(fenqiang).concat(arr)

    try {
      const mainBg = await getURLBase64Image(
        "https://imgage.maimaihao.com/makeImg/hepingNew/titleImgBgnew.png"
      );
      const canvas = document.createElement("canvas");
      const context = canvas.getContext("2d");
      canvas.width = mainBg.width;
      canvas.height = mainBg.height;
      context.drawImage(mainBg, 0, 0, mainBg.width, mainBg.height);
      context.fillStyle = "#ffffff";
      // // 头部标题 店铺名
      // context.font = "bold 50px Adobe Ming Std";
      // // 头部标题 店铺名
      // context.fillText(
      //   `${data.gameName || "--"}`,
      //   2560 / 2 - (data.gameName.length * 48) / 2,
      //   70
      // );
      // 左侧展示
      context.font = "bold 40px Adobe Ming Std";
      // 编号、区服、套装、枪皮、载具、粉装、王者印记、实名
      context.fillText(`${data.thirdId || "--"}`, 216, 368); //编号
      context.fillText(
        `${data.systemName + data.carrierName || "--"}`,
        216,
        472
      ); //区服
      context.fillText(`${data.f8 || "--"}`, 216, 585); //套装
      context.fillText(`${data.f9 || "--"}`, 216, 690); //枪皮
      context.fillText(`${data.f7 || "--"}`, 216, 800); //载具
      context.fillText(`${data.f11 || "--"}`, 268, 910); //粉装
      context.fillText(`${ data.f26||"--"}`, 216, 1015); //粉枪
      context.fillText(`${ zsk||"--"}`, 268, 1120); //粉枪
      // context.fillText(`${sm || "--"}`, 140, 1154); //实名
      //  加载皮肤图片
      context.font = "28px Adobe Ming Std";
      let skinImgs = [];
      if (arr && arr.length) {
        let temp  = uniqueBySid(arr)
        console.log("%c Line:105 🌭 temp", "color:#93c0a4", temp);
        // 按皮肤颜色排序
        // temp.sort((a, b) => {return (b.kz1||0) - (a.kz1||0)});
        console.log("%c Line:107 🥪 arr", "color:#465975", temp);
        // let temp = uniqueBySid(arr)
        // console.log("%c Line:109 🎂 temp", "color:#b03734", temp);
        // console.log("%c Line:90 🍭 排序过后的arr", "color:#fca650", arr);
        skinImgs = await loadImages(temp, 35);
      } else {
        // 没有Sren
      }
      // .sort(sortBy("sort"))
      // let instances = skinImgs.length ? skinImgs : [];
      if (skinImgs && skinImgs.length) {
        // 开始绘制
        // startX,startY,rowNum,borderImg,imgWidth1,imgHeight,stepY,stepX
        // 下载皮肤背景图
        let defaultSkinbg = await getURLBase64Image(
          "https://imgage.maimaihao.com/makeImg/hepingNew/lanse.png"
        );
        let bg1 = await getURLBase64Image(
          "https://imgage.maimaihao.com/makeImg/heping/zisebg.png"
        );
        let bg2 = await getURLBase64Image(
          "https://imgage.maimaihao.com/makeImg/hepingNew/fense.png"
        );
        let bg3 = await getURLBase64Image(
          "https://imgage.maimaihao.com/makeImg/heping/hongse.png"
        );
        // let bg4 = await getURLBase64Image(
        //   "https://imgage.maimaihao.com/makeImg/hepingNew/lanse.png"
        // );
      

        let opts = {
          startX: 524,
          startY: 194,
          rowNum: 7,
          stepY: 16,
          stepX: 15,
          txtLineHeight: 20,
          imgWidth1: 269,
          imgHeight: 225,
          bgImgs: [defaultSkinbg, defaultSkinbg, defaultSkinbg, defaultSkinbg, bg1, bg2, bg3],
          txtInside: true,
          defaultSkinbg: defaultSkinbg,
          gameId: 2,
          textColor:'#fff'
        };
        drawImagesAreaBg(context, skinImgs, opts);
        // 绘制结束
        const base64Url = canvas.toDataURL("image/jpeg", 0.8);
        resolve(base64Url);
      } else {
        const base64Url = canvas.toDataURL("image/jpeg", 0.8);
        resolve(base64Url);
      }
    } catch (error) {
      reject(error);
    }
  });
}
// 生成和平精英首图  暂时废弃
export async function makeTitleImgHpjy2(data, list, attrs) {
  // console.log("%c Line:12 🌰 attrs", "color:#2eafb0", attrs);
  // console.log("%c Line:12 🥛 list", "color:#ea7e5c", list);
  // console.log("%c Line:12 🍅 data", "color:#33a5ff", data);
  // console.log("%c Line:6 🍊 attrs", "color:#93c0a4", attrs);
  // data = smock.data
  // list = smock.list
  // attrs = smock.attrs
  return new Promise(async (resolve, reject) => {
    // 取出已选择项
    let arr = [];
    let sm = "";
    let zsk = "";
    list = list.split(",");
    if (!list || list == []) {
      reject("多选不能为空");
    }
    if (list && list.length) {
      attrs.forEach(async (item1) => {
        if (item1.aavName == "f10") {
          item1.childAttributes.forEach(async (item2) => {
            if (item2.id == data.f10) {
              sm = item2.fieldName;
            }
          });
        }
        if (item1.aavName == "f14") {
          item1.childAttributes.forEach(async (item2) => {
            if (item2.id == data.f14) {
              zsk = item2.fieldName;
            }
          });
        }
        if (item1.fieldType == "checkbox" && item1.isEnable === "0") {
          item1.childAttributes.forEach(async (item2) => {
            if (list.indexOf(String(item2.id)) > -1 && item2.imgUrl) {
              arr.push(item2);
            }
          });
        }
      });
    }

    try {
      const mainBg = await getURLBase64Image(
        "https://imgage.maimaihao.com/makeImg/heping/hepingBg3.png"
      );
      const canvas = document.createElement("canvas");
      const context = canvas.getContext("2d");
      canvas.width = mainBg.width;
      canvas.height = mainBg.height;
      context.drawImage(mainBg, 0, 0, mainBg.width, mainBg.height);
      context.fillStyle = "#ffffff";
      // 头部标题 店铺名
      context.font = "bold 50px Adobe Ming Std";
      // 头部标题 店铺名
      context.fillText(
        `${data.gameName || "--"}`,
        2560 / 2 - (data.gameName.length * 48) / 2,
        70
      );
      // 左侧展示
      context.font = "bold 40px Adobe Ming Std";
      // 编号、区服、套装、枪皮、载具、粉装、王者印记、实名
      context.fillText(`编号: ${data.thirdId || "--"}`, 140, 290); //编号
      context.fillText(
        `区服: ${data.systemName + data.carrierName || "--"}`,
        140,
        413
      ); //区服
      context.fillText(`战神框: ${zsk || "--"}`, 140, 536); //战神框
      context.fillText(`特效枪: ${data.f12 || "--"}`, 140, 660); //特效枪
      context.fillText(`载具: ${data.f7 || "--"}`, 140, 783); //载具
      context.fillText(`粉装: ${data.f11 || "--"}`, 140, 908); //粉装
      context.fillText(`王牌印记: ${data.f16 || "--"}`, 140, 1031); //王者印记
      context.fillText(`实名: ${sm || "--"}`, 140, 1154); //实名
      //  加载皮肤图片
      context.font = "25px Adobe Ming Std";
      let skinImgs = [];
      if (arr && arr.length) {
        // 按皮肤颜色排序
        arr.sort((a, b) => {return (b.kz1||0) - (a.kz1||0)});
        console.log("%c Line:90 🍭 排序过后的arr", "color:#fca650", arr);
        skinImgs = await loadImages(arr, 35);
      } else {
        // 没有Sren
      }
      // .sort(sortBy("sort"))
      // let instances = skinImgs.length ? skinImgs : [];
      if (skinImgs && skinImgs.length) {
        // 开始绘制
        // startX,startY,rowNum,borderImg,imgWidth1,imgHeight,stepY,stepX
        // 下载皮肤背景图
        let defaultSkinbg = await getURLBase64Image(
          "https://imgage.maimaihao.com/makeImg/defaultSkinbg.png"
        );
        let bg1 = await getURLBase64Image(
          "https://imgage.maimaihao.com/makeImg/heping/heping-lan.png"
        );
        let bg2 = await getURLBase64Image(
          "https://imgage.maimaihao.com/makeImg/heping/heping-fen.png"
        );
        let bg3 = await getURLBase64Image(
          "https://imgage.maimaihao.com/makeImg/heping/heping-cheng.png"
        );
        // let bg4 = await getURLBase64Image(
        //   "https://imgage.maimaihao.com/makeImg/wuWeiQiYue/skinbg4.png"
        // );
        // let bg5 = await getURLBase64Image(
        //   "https://imgage.maimaihao.com/makeImg/wuWeiQiYue/skinbg5.png"
        // );

        let opts = {
          startX: 650,
          startY: 198,
          rowNum: 7,
          stepY: 16,
          stepX: 28,
          txtLineHeight: 17,
          imgWidth1: 232,
          imgHeight: 190,
          bgImgs: [bg1, bg1, bg1, bg1, bg1, bg2, bg3],
          txtInside: true,
          defaultSkinbg: defaultSkinbg,
          gameId: 2,
        };
        drawImagesAreaBg(context, skinImgs, opts);
        // 绘制结束
        const base64Url = canvas.toDataURL("image/jpeg", 0.8);
        resolve(base64Url);
      } else {
        const base64Url = canvas.toDataURL("image/jpeg", 0.8);
        resolve(base64Url);
      }
    } catch (error) {
      reject(error);
    }
  });
}


// // 生成详情图-和平精英 多图
export async function makeDetailImgHPJY(data, skins, attrs) {
  // console.log("%c Line:147 🍯 attrs", "color:#3f7cff", attrs);
  // console.log("%c Line:147 🍢 skins", "color:#2eafb0", skins);
  // console.log("%c Line:147 🥪 data", "color:#2eafb0", data);
  // data = smock.xqData
  // skins = smock.skins
  // attrs = smock.xqAttrs
  return new Promise(async (resolve, reject) => {
    // 处理实名
    // let shimingList = attrs.filter((i) => {
    //   return i.aavName == "f1";
    // });
    // let sm = "";
    // if (shimingList.length && data.f1) {
    //   sm = shimingList[0].childAttributes.filter((i) => {
    //     return i.id == data.f1;
    //   });
    // }

    // data.sm = sm && sm.length ? sm[0].fieldName : "--";

    // 分页数据
    let {opts,imgPageArr} = await setPageImgArr(skins,{
      headHeight:660
    })
    // 下载背景图
    let defaultSkinbg = await getURLBase64Image(
      "https://imgage.maimaihao.com/makeImg/hepingNew/lanse.png"
    );
    let bg1 = await getURLBase64Image(
      "https://imgage.maimaihao.com/makeImg/heping/zisebg.png"
    );
    let bg2 = await getURLBase64Image(
      "https://imgage.maimaihao.com/makeImg/hepingNew/fense.png"
    );
    let bg3 = await getURLBase64Image(
      "https://imgage.maimaihao.com/makeImg/heping/hongse.png"
    );


    // 绘制图片
    let imgsArr = [];
    if (imgPageArr && imgPageArr.length) {
      // console.log("%c Line:184 🥪 imgPageArr", "color:#465975", imgPageArr);
      for (let k = 0; k < imgPageArr.length; k++) {
        let base64Img = await makeDetailImgWwqyOne(
          imgPageArr[k],
          data,
          [defaultSkinbg, defaultSkinbg, defaultSkinbg, defaultSkinbg, defaultSkinbg, bg1, bg2, bg3],
          defaultSkinbg,
          opts,
        );
        imgsArr.push(JSON.stringify(base64Img));
        if (k == imgPageArr.length - 1) {
          resolve(imgsArr);
        }
      }
    }
  });
}
// 绘制一个 和平精英 详情图
async function makeDetailImgWwqyOne(typeArr, data, bgImgs, defaultSkinbg,opts) {
  ////console.log("%c Line:203 🍌 typeArr", "color:#93c0a4", typeArr);
  // 先计算当前页图片的高度
  let lineHeight = opts.skinHeight||170;
  let skinHeight = 0;
  let lineNum = 0;
  let skinNum = 0;
  if (typeArr && typeArr.length) {
    for (let i = 0; i < typeArr.length; i++) {
      let typeMap = typeArr[i];
      lineNum = lineNum + Math.ceil(typeMap.skins.length / 7);
      for (let j = 0; j < typeArr[i].skins.length; j++) {
        let url = typeArr[i].skins[j].imgUrl;
        if (url) {
          try {
            skinNum++;
            const temp = await getURLBase64Image(url);
            typeArr[i].skins[j].image = temp;
          } catch (error) {}
        } else {
          typeArr[i].skins.splice(j, 1);
          j--;
        }
      }
    }
  }
  skinHeight = Math.ceil(lineNum * lineHeight) + typeArr.length * opts.typeNameHwight + opts.headHeight; //所有皮肤 包括分类标题的高度  页尾距离
  // 开始创建画布
  let y = 628; //图的绘制时距离上端的距离
  let x = 75; //绘制皮肤时的x距离
  // 创建canvas实例
  const canvas = document.createElement("canvas");
  canvas.style.background = "#233D57";
  const context = canvas.getContext("2d");
  canvas.width = 1500;
  canvas.height = Math.ceil(skinHeight);
  context.font = "40px Adobe Ming Std";
  // 下载分类名称背景
  let typeNameBg = await getURLBase64Image(
    "https://imgage.maimaihao.com/makeImg/hepingNew/detailClassBg.png"
  );
  // 下载主背景
  let mainBgImg = await getURLBase64Image(
    "https://imgage.maimaihao.com/makeImg/hepingNew/hepingDetailImgBg.png"
  );
  // 下载基础皮肤背景
  let baseBg = await getURLBase64Image(
    "https://imgage.maimaihao.com/makeImg/hepingNew/skinbg2.png"
  );
  // // 下载右上角装饰
  // let hpjyrg = await getURLBase64Image(
  //   "https://imgage.maimaihao.com/makeImg/heping/hpjyrg.png"
  // );
  // 开始绘制
  // 绘制整体背景色
  drawBgBorder(context, 0, 0, canvas.width, skinHeight, {
    radius: 0,
    borderWidth: 0,
    startColor: "#233D57",
    centerColor1: "#233D57",
    centerColor2: "#233D57",
    endColor: "#233D57",
    borderColor: "#233D57",
  });

  // 绘制背景图
  context.drawImage(mainBgImg, 0, 0, canvas.width, 1530);
  // // 绘制标题背景
  // context.drawImage(titleBg, 0, 0, canvas.width, 100);
  // // 填充标题文字
  // context.font = "bold 30px Adobe Ming Std";
  // context.fillStyle = "#fff"; // 文字填充颜色
  // // 头部标题 店铺名
  // context.fillText(
  //   `${data.gameName || "--"}`,
  //   canvas.width / 2 - (data.gameName.length * 30) / 2,
  //   50
  // );

  // 绘制主要区域的背景
  drawBgBorder(context, 38, 590, canvas.width - 76, skinHeight - 620, {
    radius: 12,
    borderWidth: 1,
    startColor: "#B5A7E6",
    centerColor1: "#B0D4CC",
    centerColor2: "#E5DDEE",
    endColor: "#E7FAE6",
    borderColor: "#FFF6E9",
  });
  // 绘制右上角装饰 hpjyrg
  // context.drawImage(hpjyrg, 1482, 130, 5, 68);

  // 头部展示字段
  context.fillStyle = "#fff"; // 文字填充颜色
  context.font = "bold 40px Adobe Ming Std";
  // 编号、区服、套装、枪皮、载具、粉装、王者印记、实名
  context.fillText(`${data.thirdId || "--"}`, 681, 323); //编号
  context.fillText(
    `${data.systemName + data.carrierName || "--"}`,
    681,
    393
  ); //区服
  context.fillText(`${data.f8 || "--"}`, 681, 463); //套装
  context.fillText(`${data.f9 || "--"}`, 681, 533); //枪皮
  context.fillText(`${data.f7 || "--"}`, 1056, 323); //载具
  context.fillText(`${data.f11 || "--"}`, 1089, 393); //粉装
  context.fillText(`${ data.f12||"--"}`, 1056, 463); //粉枪
  //
  // 开始绘制皮肤
  if (typeArr && typeArr.length) {
    for (let i = 0; i < typeArr.length; i++) {
      let typeMap = typeArr[i];
      for (let j = 0; j < typeMap.skins.length; j++) {
        let skin = typeMap.skins[j];
        if (j == 0) {
          // 分组开始  先绘制分类标题图片和分类名
          if (i != 0) {
            y += lineHeight;
          }
          context.drawImage(typeNameBg, 75, y, 1300, 60);
          context.font = "28px Adobe Ming Std";
          context.fillStyle = "#ffffff"; // 文字填充颜色
          let name = typeMap.typeName || "其他";
          // let txtWidth = name.length * 28;
          context.fillText(` ${name}`, 140, y + 40);
          y += 75;
          x = 75;
        }
        if (j % 7 == 0 && j != 0) {
          x = 75;
          y += lineHeight;
        }
        if (j % 7 == 0 ) {
          // 绘制一行7个基础图
          let rowx = x
          for (let l = 0; l < 7; l++){
            context.drawImage(baseBg, rowx, y, 185, 151);
            rowx += 193;
          }
        }
        // 绘制每张图中的皮肤
        if (skin.image) {
          // 绘制背景图
          if (skin.kz1 && bgImgs[skin.kz1]) {
            const bg = bgImgs[skin.kz1];
            // console.log("%c Line:223 🌭 bg", "color:#f5ce50", bg);
            context.drawImage(bg, x, y, 185, 151);
            context.fillStyle = "#fff"; // 文字填充颜色
          } else {
            if (defaultSkinbg) {
              context.drawImage(defaultSkinbg, x, y, 185, 151);
              context.fillStyle = "#fff"; // 文字填充颜色
            }
          }
          // 绘制皮肤图片
          context.drawImage(skin.image, x + 40, y + 10, 105, 100);
          // 皮肤名称
          context.font = "22px Adobe Ming Std";
          context.fillText(
            ` ${skin.fieldName ? skin.fieldName : "未知"}`,
            x,
            y + 138
          );

          // 右上角等级
          if (skin.kz2) {
            context.fillStyle = "#333";
            context.fillText(skin.kz2 + "级", x + 185 - 60, y + 20);
          }
          x += 193;
        }
      }
    }
  }
  return canvas.toDataURL("image/jpeg", 1);
}
